﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Ink;
using System.Xml;
using System.Runtime.Serialization;
using xml_classes;
using Polygon = System.Windows.Shapes.Polygon;

namespace editor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 
    public partial class MainWindow : Window
    {
        private ScreenFromEditor _screen = new ScreenFromEditor();      
        bool drawing_polygon = false;
        List<xml_classes.Polygon> polygons;
        Polygon ghost;
        private ImageFitToScreen _GameScreen = new ImageFitToScreen("Background", "", 0, 0);
        private ImageFitToScreen _WalkingMap = new ImageFitToScreen("WalkingMap", "", 0, 0);

        DrawingAttributes inkAttributes = new DrawingAttributes();
        public MainWindow()
        {
            InitializeComponent();
            polygons = new List<xml_classes.Polygon>();
            inkCanvas1.DefaultDrawingAttributes = inkAttributes;
        }

        private void ChangeColor(object sender, RoutedEventArgs e)
        {
            SolidColorBrush solidBrush = ((Button)sender).Background as SolidColorBrush;
            StrokeCollection SC = inkCanvas1.GetSelectedStrokes();
            if (SC.Count == 0)
            {
                inkAttributes.Color = solidBrush.Color;
                inkAttributes.IsHighlighter = false;
            }
            else
            {
                for (int i = 0; i < SC.Count; i++)
                {
                    SC.ElementAt(i).DrawingAttributes.Color = solidBrush.Color;
                }
            }
        }

        void eraseByPointEditingMode_Click(object sender, RoutedEventArgs e)
        {
            inkCanvas1.EditingMode = InkCanvasEditingMode.EraseByPoint;
        }

        void eraseByStrokeEditingMode_Click(object sender, RoutedEventArgs e)
        {
            inkCanvas1.EditingMode = InkCanvasEditingMode.EraseByStroke;
        }

        void selectEditingMode_Click(object sender, RoutedEventArgs e)
        {
            inkCanvas1.EditingMode = InkCanvasEditingMode.Select;
        }

        void inkEditingMode_Click(object sender, RoutedEventArgs e)
        {
            inkCanvas1.EditingMode = InkCanvasEditingMode.Ink;
        }

        void radioButton0_Checked(object sender, RoutedEventArgs e)
        {
            inkCanvas1.EditingMode = InkCanvasEditingMode.None;
        }

        void SetBackground(string path)
        {
            ImageBrush berriesBrush = new ImageBrush();
            berriesBrush.ImageSource =
                new BitmapImage(
                    new Uri(path, UriKind.Relative)
                );
            _GameScreen = new ImageFitToScreen("Background", path, berriesBrush.ImageSource.Width, berriesBrush.ImageSource.Height);
            inkCanvas1.Background = berriesBrush;
        }

        private void LoadBackgroundImage(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".jpg";
            dlg.Filter = "JPG Files (*.jpg)|*.jpg";


            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();


            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                string filename = dlg.FileName;
                SetBackground(filename);
            }
        }

        private void SaveWork(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog 
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".isf";
            dlg.Filter = "ISF Files (*.isf)|*.isf";


            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();


            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                writeEditorFile(dlg.FileName);
            }
        }

        private void writeEditorFile(string filename)
        {
            using (FileStream fs = new FileStream(filename, FileMode.Create))
            {
                inkCanvas1.Strokes.Save(fs);
                fs.Close();
            }
        }

        private void LoadAndRunOverWork(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".isf";
            dlg.Filter = "ISF Files (*.isf)|*.isf";


            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();


            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                string filename = dlg.FileName;

                FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                StrokeCollection strokes = new StrokeCollection(fs);
                inkCanvas1.Strokes = strokes;
                fs.Close();
            }
        }

        private void LoadAndAddWork(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".isf";
            dlg.Filter = "ISF Files (*.isf)|*.isf";


            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();


            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                string filename = dlg.FileName;

                FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                StrokeCollection strokes = new StrokeCollection(fs);
                for (int i = 0; i < strokes.Count; i++)
                {
                    inkCanvas1.Strokes.Add(strokes.ElementAt(i));
                }
                fs.Close();
            }
        }

        private void AllDone(object sender, RoutedEventArgs e)
        {
            DirectoryInfo DI = new DirectoryInfo(Directory.GetCurrentDirectory());
            //DI = DI.Parent.Parent;

            Directory.CreateDirectory(DI.FullName + @"\GameScreens\" + textBox1.Text + @"\");

            string RelativePathOfWalkingMap = DI.FullName + @"\GameScreens\" + textBox1.Text + @"\" + textBox1.Text + "_WalkingMap.Bmp";
            string RelativePathOfScreensProperties = DI.FullName + @"\GameScreens\" + textBox1.Text + @"\" + textBox1.Text + "_ScreensProperties.Xml";
            string RelativePathOfScreenBackgroud = DI.FullName + @"\GameScreens\" + textBox1.Text + @"\" + textBox1.Text + "_ScreenBackgroud.Jpg";
            string RelativePathOfScreensEditorFile = DI.FullName + @"\GameScreens\" + textBox1.Text + @"\" + textBox1.Text + "_ScreensEditorFile.isf";

            SaveAsBMP(RelativePathOfWalkingMap);
            writeDataToXML(RelativePathOfScreensProperties);
            writeEditorFile(RelativePathOfScreensEditorFile);
            if (File.Exists(_GameScreen.GetPath()))
	        {
                File.Copy(_GameScreen.GetPath(), RelativePathOfScreenBackgroud);
	        }
            
        }

        private void SaveAsBMP(string path)
        {
            
            RenderTargetBitmap rtb = new RenderTargetBitmap((int)this.inkCanvas1.ActualWidth, (int)this.inkCanvas1.ActualHeight, 0, 0, PixelFormats.Pbgra32);

            StrokeCollection TempStrokeCollection = inkCanvas1.Strokes.Clone();
            Brush TempBrush = null;
            if (inkCanvas1.Background != null)
            {
                TempBrush = inkCanvas1.Background.Clone();
            }

            inkCanvas1.Background = null;
            inkCanvas1.UpdateLayout();
            for (int i = 0; i < inkCanvas1.Strokes.Count; i++)
            {
                if (IsStrokeAPolygon(inkCanvas1.Strokes.ElementAt(i)))
                {
                    inkCanvas1.Strokes.Remove(inkCanvas1.Strokes.ElementAt(i));
                    i--;
                }
                else
                {
                    inkCanvas1.Strokes.ElementAt(i).DrawingAttributes.Color = Colors.White;
                }
            }

            rtb.Render(this.inkCanvas1);

            this.inkCanvas1.Strokes = TempStrokeCollection;
            inkCanvas1.Background = TempBrush;

            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(rtb));
            FileStream file = new FileStream(path, FileMode.Create);
            encoder.Save(file);
            file.Close();

            _WalkingMap = new ImageFitToScreen("WalkingMap", path, inkCanvas1.Width, inkCanvas1.Height);

        }

        private void RemoveBackgroundImage(object sender, RoutedEventArgs e)
        {
            _GameScreen = new ImageFitToScreen("Background", "", 0, 0);
            inkCanvas1.Background = null;
        }

        private void SetThickness(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            inkAttributes.Width = ((Slider)sender).Value;
            inkAttributes.Height = ((Slider)sender).Value;
            inkCanvas1.EraserShape = new RectangleStylusShape(((Slider)sender).Value, ((Slider)sender).Value);
            var editMode = inkCanvas1.EditingMode;
            inkCanvas1.EditingMode = InkCanvasEditingMode.None;
            inkCanvas1.EditingMode = editMode;
        }

        private void EraseAll(object sender, RoutedEventArgs e)
        {
            inkCanvas1.Strokes.Clear();
        }

        private void inkCanvas1_SelectionChanged(object sender, EventArgs e)
        {
            StrokeCollection SC = inkCanvas1.GetSelectedStrokes();
            if (SC.Count == 0)
            {
                button17.IsEnabled = false;
            }
            else
            {
                button17.IsEnabled = true;
            }
        }

        private void EraseSelection(object sender, RoutedEventArgs e)
        {
            StrokeCollection SC = inkCanvas1.GetSelectedStrokes();
            if (SC.Count != 0)
            {
                for (int i = 0; i < SC.Count; i++)
                {
                    inkCanvas1.Strokes.Remove(SC.ElementAt(i));
                }
                button17.IsEnabled = false;
            }
        }

        private void inkCanvas1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!drawing_polygon)
            {
                return;
            }
            if (ghost.Points.Count > 0)
            {
                ghost.Points.RemoveAt(ghost.Points.Count - 1);
                ghost.Points.Add(Mouse.GetPosition(inkCanvas1));
            }
        }

        private void inkCanvas1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (drawing_polygon)
            {
                ghost.Points.RemoveAt(ghost.Points.Count - 1);

                ghost.Stroke = Brushes.Yellow;

                inkCanvas1.Children.Remove(ghost);

                StylusPointCollection SPC = new StylusPointCollection();
                for (int i = 0; i < ghost.Points.Count; i++)
                {
                    SPC.Add(new StylusPoint(ghost.Points.ElementAt(i).X, ghost.Points.ElementAt(i).Y));
                }
                SPC.Add(new StylusPoint(ghost.Points.ElementAt(0).X, ghost.Points.ElementAt(0).Y));
                Stroke stroke1 = new Stroke(SPC);

                stroke1.DrawingAttributes.IsHighlighter = true;
                stroke1.DrawingAttributes.Color = inkAttributes.Color;
                stroke1.DrawingAttributes.Width = 5;
                stroke1.DrawingAttributes.Height = 5;


                inkCanvas1.Strokes.Add(stroke1);
                drawing_polygon = false;
                polygons.Add(new xml_classes.Polygon(stroke1.StylusPoints, stroke1.DrawingAttributes.Color.ToString()));
                ghost = null;
            }
        }

        private void radioButton0_Unchecked(object sender, RoutedEventArgs e)
        {
            if (drawing_polygon == true)
            {
                inkCanvas1.Children.Remove(ghost);
                ghost = null;
                drawing_polygon = false;
            }
        }

        private void inkCanvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ghost == null)
            {
                drawing_polygon = true;
                ghost = new Polygon();
                ghost.Stroke = Brushes.Aqua;
                ghost.StrokeThickness = 2;
                inkCanvas1.Children.Add(ghost);
            }
            if (inkCanvas1.EditingMode == InkCanvasEditingMode.None)
            {
                if (!drawing_polygon)
                {
                    return;
                }
                ghost.Points.Add(Mouse.GetPosition(inkCanvas1));
                if (ghost.Points.Count == 1)
                    ghost.Points.Add(Mouse.GetPosition(inkCanvas1));
            }
        }

        private void writeDataToXML(string path)
        {
            _screen._GameScreen = _GameScreen;
            _screen._WalkingMap = _WalkingMap;
            _screen._polygons = polygons;
            XMLmanager.Serialize(_screen, @"c:\XMLFromEditor.xml");
            
            
            XmlTextWriter textWriter = new XmlTextWriter(path, null);
            // Opens the document
            textWriter.WriteStartDocument();
            textWriter.WriteStartElement("Screen");
            _GameScreen.WriteAsXML(textWriter);
            _WalkingMap.WriteAsXML(textWriter);

            if (inkCanvas1.Strokes.Count > 0)
            {
                bool bPolygonFound = false;
                //write polygons
                foreach (Stroke stroke in inkCanvas1.Strokes)
                {
                    if (IsStrokeAPolygon(stroke))
                    {
                        if (!bPolygonFound)
                        {
                            bPolygonFound = true;
                            textWriter.WriteStartElement("Polygons");
                        }
                        stroke.WriteAsXML(textWriter);
                    }
                }
                if (bPolygonFound)
                {
                    textWriter.WriteEndElement();
                }
            }

            // Ends the document.
            textWriter.WriteEndDocument();
            // close writer
            textWriter.Close();
        }

        static bool IsStrokeAPolygon(Stroke stroke)
        {
            if (stroke.DrawingAttributes.IsHighlighter)
            {
                return true;
            }
            return false;
        }

        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (((TextBox)sender).Text.Equals(""))
            {
                button2.IsEnabled = false;
            }
            else
            {
                button2.IsEnabled = true;
            }
        }




    }
}
